<?php
class AdminController extends AppController {
	public $helpers = array (
			'Html',
			'Form',
			'Session'
	);
	//set name of the layout
	public $layout = 'admin';

	public function index() {
		
		
		$userLogin = $this->Auth->user();
		$userId = $userLogin['id'];
		
		//check authority
		
		
		//set data for profile.ctp
		$this->set('user', $userLogin);
		$this->loadModel('Post');
		$this->set('created', $this->Post->findAllCreatedPost($userId));
// 		$allPost = $this->Post->find ( 'all', array (
// 				'conditions' => array (
// 						'Post.user_id' => $userId
// 				)) );
		
// 		foreach ($allPost as $key => $post){
// 			$bodytext = $post['Post']['body'];
// 			$bodyS = $this->reviewText ( 100, $bodytext );
// 			$allPost[$key]['Post']['body'] = $bodyS;
// 		}
		
		//set data for profile.ctp		
// 		$this->set('isAuthor',$isAuthor);
// 		$this->set('allCreatedPosts', $allPost);
// 		echo '<pre>';
// 		print_r($this->getAllDataPaging());
// 		exit;
		$this->set('posts', $this->getAllDataPaging());
		$this->set('chartData', $this->getChartData($userId));
	}
	
	private function getAllDataPaging() {
		$this->paginate = array(
				'limit' => 5,
				'order' => 'Post.modified DESC'
		);
		try {
			return $this->paginate ( 'Post' );
		} catch ( NotFoundException $e ) {
			return $this->render('/errors/error');
		}
	}
	
	private function getChartData($userId = null) {
		// find all the date this user create post, group by created date
		$results = $this->Post->find ( 'all', array (
				'conditions' => array (
						'Post.user_id' => $userId
				),
				'fields' => array (
						'DATE(Post.created) AS created',
						'COUNT(*) AS quantity'
				),
				'group' => array (
						'DATE(Post.created)'
				),
				'order' => array (
						'DATE(Post.created) ASC'
				)
		) );
	
		// group the result again, this time by month_year
		$monthYearGroup = array ();
		App::uses ( 'CakeTime', 'Utility' );
		$dummyStr = "";
		$tempCount = 0;
	
		for($i = 0; $i < sizeof ( $results ); $i ++) {
			$rTime = CakeTime::format ( $results [$i] [0] ['created'], '%B_%Y' );
	
			//check whether the value month_year is stored in $monthYearGroup array, use another temp string
			if (strpos ( $dummyStr, $rTime ) === false) {
				$dummyStr = $dummyStr . $rTime . ' ';
	
				// sum the quantity of equal-month_year records
				for($j = $i; $j < sizeof ( $results ); $j ++) {
					$rTimeChild = CakeTime::format ( $results [$j] [0] ['created'], '%B_%Y' );
	
					if ($rTimeChild == $rTime) {
						$tempCount = $tempCount + $results [$j] [0] ['quantity'];
					} else {
						break;
					}
				}
	
				// store the new month_year time and quantity into array
				array_push ( $monthYearGroup, array (
				'dateTime' => $rTime,
				'quantity' => $tempCount
				) );
				$tempCount = 0;
			}
		}
	
		//json encode for data chart
		$chartData ['cols'] = array (
				array (
						'id' => 'created',
						'label' => 'Date',
						'type' => 'string'
				),
				array (
						'id' => 'quantity',
						'label' => 'Posted',
						'type' => 'number'
				)
		);
		foreach ( $monthYearGroup as $result ) {
			// $time = strtotime ( $result [0] ['created'] );
			// $dateJs = 'Date(' . date ( "Y", $time ) . ', ' . (date ( 'n', $time ) - 1) . ', ' . date ( 'j', $time ) . ')';
			$row = array (
					'c' => array (
							array (
									'v' => $result ['dateTime']
							),
							array (
									'v' => $result ['quantity']
							)
					)
			);
			$chartData ['rows'] [] = $row;
		}
		return json_encode ( $chartData ) ;
	}
	
	public function edit($id = null) {
	
		// check params
		if (!$id) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
	
		//Load model Post
		$this->loadModel('Post');
	
	
		$post = $this->Post->findById ( $id );
		if (! $post) {
			throw new NotFoundException ( __ ( 'Invalid post' ) );
		}
	
	
		// save to db
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			$this->Post->id = $id;
			if ($this->Post->save ( $this->request->data )) {
				$this->Session->setFlash ( 'Your post has been updated', 'default', array (
						'class' => 'alert alert-success'
				) );
				return $this->redirect ( array (
						'controller' => 'posts',
						'action' => 'detail',
						$id
				) );
			}
			$this->Session->setFlash ( 'Unable to update your post', 'default', array (
					'class' => 'alert alert-danger'
			) );
		}
		// initialize value if update date is not available
		if (! $this->request->data) {
			$this->request->data = $post;
		}
		// reder view layout for edit
		$this->set ( 'post', $post );
	}
	
	/**
	 * Method delete post
	 */
	public function delete($id = null) {
	
		// check request method, if not 'Post' throw error
		if ($this->request->is ( 'get' )) {
			throw new MethodNotAllowedException ();
		}
	
		// delete data in db, cascade setting help delete depedent child data
		$this->loadModel('Post');
	
	
		if ($this->Post->delete ( $id )) {
			$this->Session->setFlash ( 'Deleted', 'default', array (
					'class' => 'alert alert-success'
			) );
			return $this->redirect ( array (
					'controller' => 'admin',
					'action' => 'index'
			) );
		}
	}
	
}